import Vue from 'vue'
import Vuex, {ActionTree, GetterTree, Module, ModuleTree, MutationTree, StoreOptions} from 'vuex'
import createPersistedState from "vuex-persistedstate"
import {Decrypt3Des,Encrypt3Des} from '@/libs/tool'
import Global from '@/config/global'

//引入Vuex组件
Vue.use(Vuex);

//动态获取组件
const requireComponent = require.context('@/store', true, /\.(ts|js)$/);

//定义
let options:StoreOptions<any>={};
let state:any={};
let getters:GetterTree<any,any>={};
let actions:ActionTree<any,any>={};
let mutations:MutationTree<any>={};
let modules:ModuleTree<any>={};

//去掉vuex严格验证
options.strict=false;

//动态注册vuex
requireComponent.keys().forEach(fileName => {
   let name= (fileName.split("/").pop() as string).replace(/\.\w+$/, '').toLowerCase();
   if(name=="index"){//如果是index,则导入全局
      const componentDefault=requireComponent(fileName).default;
      if(componentDefault){//如果不是空文件
         state=(componentDefault.state)?componentDefault.state:{};
         getters=(componentDefault.getters)?componentDefault.getters:{};
         actions=(componentDefault.actions)?componentDefault.actions:{};
         mutations=(componentDefault.mutations)?componentDefault.mutations:{};

      }
   }else if(requireComponent(fileName).default){//有导出文件
      let componentDefault:Module<any,any>=requireComponent(fileName).default;
      componentDefault.namespaced=true;
      modules[name]=componentDefault;
   }else{//空文件
      modules[name]={};
   }
});

//构建vuex配置
options.state=state;
options.getters=getters;
options.actions=actions;
options.mutations=mutations;
options.modules=modules;
options.plugins=[
   createPersistedState({
      storage: window.sessionStorage,
      getState: function (key) {
         let stateObj = window.sessionStorage.getItem(Global.desName);
         if (stateObj) {
            return JSON.parse(Decrypt3Des(stateObj, Global.desKey, Global.desIv));
         } else {
            return {};
         }
      },
      setState: function (key, value) {
         let state = Encrypt3Des(JSON.stringify(value), Global.desKey, Global.desIv);
         return sessionStorage.setItem(Global.desName, state);
      }
   })
];

//创建新的vuex
let Store=new Vuex.Store(options);

export default Store;
